import { Component, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { dateFormat, deepClone, replaceAll, type } from '../../../../utils/utils';
import { ApesMessageService } from '@shared/apes/message';
import { GridConfigService } from '@core/config/grid-config.service';
import { GridOptions } from '@ag-grid-community/core';
import { HttpClient } from '@angular/common/http';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core';
import { FormGroup } from '@angular/forms';
import { ApesDrawerCustomGridComponent } from '@shared/ag-grid-ext/drawer-custom/drawer-custom-grid.component';
import { ApesDrawerService } from '@shared/apes/drawer';
import {
  RenderDetailComponent,
} from '@shared/ag-grid-ext/cell-renders/render-detail.component';

@Component({
  selector: 'state-machine',
  templateUrl: './state-machine.component.html',
  styleUrls: ['./state-machine.component.scss'],
})
export class StateMachineComponent implements OnInit {

  height: any = 500 + 'px';

  /** 按钮相关 **/
  buttonBar = [
    { hide: true, style: 'primary', label: '查询', id: 'action_query', loading: false },
  ];


  form = new FormGroup({});
  ctx = { model: {} };
  model: any = {};
  options: FormlyFormOptions = {};
  field: FormlyFieldConfig[] = [
    {
      key: 'fsmFlow#id',
      type: 'conditionInput',
      templateOptions: {
        label: '状态流',
        placeholder: '请输入状态流编码或名称',
        config: {
          api: 'fsm.fsmFlow.findAll',
          domain: '{"filters":[{"field":"id","operator":"like","value":"{{value}}"},{"field":"name","operator":"like","value":"{{value}}"}],"groups":[],"operator":"and"}',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: '\'[ \' + value.id + \' ]\' + \' \' + value.name',
          valueFormatter: '\'[ \' + value.id + \' ]\' + \' \' + value.name',
        },
      },
    },
    {
      key: 'businessKey',
      type: 'input',
      templateOptions: {
        label: '业务单号',
      },
    },
    // {
    //   key: 't3',
    //   type: 'input',
    //   templateOptions: {
    //     label: '车牌',
    //   },
    // },
    {
      key: 'createDate',
      type: 'conditionInput',
      templateOptions: {
        label: '创建时间',
        config: {
          inable: false,
          nullable: false,
          operators: ['EQ'],
          type: 'dateRange',
        }
      },
    },
  ];

  /** grid 相关 **/
  private gridApi;
  private gridColumnApi;
  frameworkComponents: any;
  modules: Module[] = AllModules;
  localeText: any;
  api = 'fsm.fsmStateLogService.findAll';
  rowData: any[] = [
    // {
    //   'suspend': false,
    //   'fsmFlow': '[000041]交货',
    //   'business': '[物流交货单]JH6083201200001',
    //   'stateList': [
    //     {
    //       'creator': '[null]2020-12-28 18:03:19.0',
    //       'finished': false,
    //       'id': '068139',
    //       'fsmState': '[000061]待交货',
    //       'updater': '[null]null',
    //       'innerBusiness': '[交货]054343',
    //     },
    //     {
    //       'creator': '[null]2020-12-28 18:03:25.0',
    //       'finished': true,
    //       'id': '068141',
    //       'fsmState': '[000062]完成',
    //       'updater': '[null]2020-12-28 18:03:25.488',
    //       'innerBusiness': '[交货]054343',
    //     },
    //     {
    //       'creator': '[null]2020-12-28 18:03:25.0',
    //       'finished': true,
    //       'id': '068140',
    //       'fsmState': '[000061]待交货',
    //       'updater': '[null]2020-12-28 18:03:25.435',
    //       'innerBusiness': '[交货]054343',
    //     },
    //     {
    //       'creator': '[null]2020-12-28 18:03:19.0',
    //       'finished': false,
    //       'id': '068139',
    //       'fsmState': '[000061]待交货',
    //       'updater': '[null]null',
    //       'innerBusiness': '[交货]054343',
    //     },
    //     {
    //       'creator': '[null]2020-12-28 18:03:19.0',
    //       'finished': false,
    //       'id': '068139',
    //       'fsmState': '[000061]待交货',
    //       'updater': '[null]null',
    //       'innerBusiness': '[交货]054343',
    //     },
    //     {
    //       'creator': '[null]2020-12-28 18:03:19.0',
    //       'finished': false,
    //       'id': '068139',
    //       'fsmState': '[000061]待交货',
    //       'updater': '[null]null',
    //       'innerBusiness': '[交货]054343',
    //     },
    //     {
    //       'creator': '[null]2020-12-28 18:03:19.0',
    //       'finished': false,
    //       'id': '068139',
    //       'fsmState': '[000061]待交货',
    //       'updater': '[null]null',
    //       'innerBusiness': '[交货]054343',
    //     },
    //     {
    //       'creator': '[null]2020-12-28 18:03:19.0',
    //       'finished': false,
    //       'id': '068139',
    //       'fsmState': '[000061]待交货',
    //       'updater': '[null]null',
    //       'innerBusiness': '[交货]054343',
    //     },
    //   ],
    //   'creator': '[null]2020-12-28 18:03:18.883',
    //   'finished': true,
    //   'id': '054343',
    //   'fsmState': '[000062]完成',
    //   'updater': '[null]2020-12-28 18:03:25.48',
    // },
    // {
    //   'suspend': false,
    //   'fsmFlow': '[000041]交货',
    //   'business': '[物流交货单]JH6083201200001',
    //   'stateList': [
    //     {
    //       'creator': '[null]2020-12-28 18:03:19.0',
    //       'finished': false,
    //       'id': '068139',
    //       'fsmState': '[000061]待交货',
    //       'updater': '[null]null',
    //       'innerBusiness': '[交货]054343',
    //     },
    //     {
    //       'creator': '[null]2020-12-28 18:03:25.0',
    //       'finished': true,
    //       'id': '068141',
    //       'fsmState': '[000062]完成',
    //       'updater': '[null]2020-12-28 18:03:25.488',
    //       'innerBusiness': '[交货]054343',
    //     },
    //     {
    //       'creator': '[null]2020-12-28 18:03:25.0',
    //       'finished': true,
    //       'id': '068140',
    //       'fsmState': '[000061]待交货',
    //       'updater': '[null]2020-12-28 18:03:25.435',
    //       'innerBusiness': '[交货]054343',
    //     },
    //   ],
    //   'creator': '[null]2020-12-28 18:03:18.883',
    //   'finished': true,
    //   'id': '054343',
    //   'fsmState': '[000062]完成',
    //   'updater': '[null]2020-12-28 18:03:25.48',
    // },
  ];
  columnDefs: any;
  detailRowHeight: any = '200';
  detailCellRendererParams: any;
  defaultColDef: any;
  gridOptions: GridOptions;
  rowModelType: any;
  isRowMaster: any;
  detailCellRenderer: any;

  /** 分页器 **/
  loadingTotal = 0;

  pagination = {
    total: 0,
    currentPage: 0,
    lastRow: -1,
    pageSize: 50,
  };


  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
              private http: HttpClient,
              protected drawerService: ApesDrawerService,
              private gridConfigService: GridConfigService) {
    this.isRowMaster = (dataItem) => {
      return dataItem ? dataItem.detailList.length > 0 : false;
    };
    this.gridOptions = <GridOptions>{
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
    };

    this.defaultColDef = { flex: 1 };
    this.columnDefs = [
      { headerName: '状态流', field: 'fsmFlow', width: 220, cellRenderer: 'agGroupCellRenderer'},
      { headerName: '状态流实例', field: 'id', width: 100 },
      { headerName: '最新状态', field: 'fsmState', width: 120 },
      { headerName: '更新', field: 'updater', width: 200 },
      { headerName: '创建', field: 'creator', width: 200 },
      { headerName: '结束', field: 'finished', width: 80 },
      { headerName: '挂起', field: 'suspend', width: 80 },
      { headerName: '业务单号', field: 'business', width: 160 },
    ];

    this.detailCellRendererParams = {
      detailList: 'detailList',
      detailRowHeight: this.detailRowHeight,
      detailGridOptions: {
        columnDefs: [
          { headerName: '状态', field: 'fsmState', width: 220 },
          {
            headerName: '状态实例',
            field: 'id',
            width: 100,
            cellRenderer: 'dialogButton',
            buttonList: [
              {
                'id': 'id',
                'name': '',
                'hide': false,
                'disabled': false,
                'action': 'drawer',
                'formId': 'fsm.stateLog',
                'api': '',
                'title': '任务信息',
                'width': '70vw',
                'link': '明细',
              }],
          },
          { headerName: '创建', field: 'creator', width: 200 },
          { headerName: '更新', field: 'updater', width: 200 },
          { headerName: '结束', field: 'finished', width: 80 },
          { headerName: '触发事件', field: 'fsmEvent', width: 160 },
          { headerName: '来源单据', field: 'innerBusiness', width: 160 },
        ],
      },
      getDetailRowData: function(params) {
        params.successCallback(params.data);
      },
    };
    this.detailCellRenderer = 'detail';
    this.frameworkComponents = { detail: RenderDetailComponent };
    this.gridOptions.localeText = gridConfigService.getLocaleText();

  }

  ngOnInit() {
    this.rowModelType = 'serverSide';
    this.gridOptions.cacheBlockSize = 50;
    this.gridOptions.infiniteInitialRowCount = 1;
    this.gridOptions.pagination = false;
    this.gridOptions.paginationPageSize = this.pagination.pageSize;
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.action_query();
      }
    }
  }

  /** 主数据 查询按钮事件 **/
  action_query() {
    this.pagination.currentPage = 0;   // 每次点击查询按钮时，重置 currentPage

    this.pagination.lastRow = -1;
    this.queryData();
  }

  queryData() {
    console.log(this.model);
    const conditionParam = this.getConditionList(this.field);

    const sendData = {};
    sendData['condition'] = conditionParam.conditionList;
    sendData['size'] = this.pagination.pageSize;
    sendData['page'] = this.pagination.currentPage;
    // sendData['queryid'] = this.api;

    let dataSource = {
      rowCount: null,
      getRows: (params: any) => this.getRows(params, [], sendData),
    };

    this.gridApi.setServerSideDatasource(dataSource);
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
  }

  /**
   * 功能：拼接查询条件
   * @returns {any[]}
   */
  getConditionList(conditionField: any): { flag: boolean, conditionList: any[] } {
    // flag 用于判断必输项是否输入完成
    let returnParam = { flag: true, conditionList: [] };
    let conditionList = [];
    for (const tempConditionField of conditionField) {
      let fieldKey = tempConditionField.key;

      let fieldValue = this.model[fieldKey];

      const  config = tempConditionField.templateOptions.config;

      // 判断查询的操作条件（=、like...）
      let operatorValue = '';

      if (fieldValue === undefined || fieldValue === null || fieldValue.length === 0) {
        continue;
      }
      // 处理存在明细表字段的情况
      fieldKey = replaceAll(fieldKey, '#', '.');

      if (config && config.type === 'dateRange') {
        const dataModelStar = {
          field: fieldKey,
          operator: 'GTE',
          value: dateFormat('yyyy-MM-dd', fieldValue[0]) + ' 00:00:00',
          type: 'date',
        };
        const dataModelEnd = {
          field: fieldKey,
          operator: 'LTE',
          value: dateFormat('yyyy-MM-dd', fieldValue[1]) + ' 23:59:59',
          type: 'date',
        };

        conditionList.push(dataModelStar);
        conditionList.push(dataModelEnd);
      } else {
        const dataModel = {};

        dataModel['field'] = fieldKey;
        dataModel['operator'] = operatorValue ? operatorValue : 'EQ';
        dataModel['value'] = type(fieldValue) == 'string' ?
          fieldValue.trim() : fieldValue;
        conditionList.push(dataModel);
      }
    }
    returnParam.conditionList = conditionList;
    return returnParam;
  }

  private getRows(params: any, data: any, sendData: any) {
    sendData['size'] = this.pagination.pageSize;
    sendData['page'] = this.pagination.currentPage;
    this.gridApi.showLoadingOverlay();
    // TODO 检查返回值是否不为空数组
    this.apiService.post('fsm.fsmStateLogService.findAll', { 'body': JSON.stringify(sendData) })
      .subscribe((items) => {
        if (items) {
          this.pagination.total = items.total;
          const itemsLength = items.content.length;
          if (itemsLength > 0 && itemsLength >= this.pagination.pageSize) {
            this.pagination.currentPage = this.pagination.currentPage + 1;
          }
          if (itemsLength == 0 || itemsLength < this.pagination.pageSize) {
            this.pagination.lastRow = this.pagination.currentPage * this.pagination.pageSize + itemsLength;
          }
          this.loadingTotal = this.pagination.lastRow !== -1 ? this.pagination.lastRow : params.request.endRow;
          params.successCallback(items.content, this.pagination.lastRow);
          if (itemsLength === 0 && this.pagination.lastRow <= 0) this.msg.info(`未找到满足条件的数据`);
        } else {
          params.successCallback([], 0);
        }
        this.gridApi.hideOverlay();
        this.buttonBar[0].loading = false;
      }, () => {
        this.buttonBar[0].loading = false;
      });
  }
}

